/**
 * 
 */
package com.manyi.ihouse.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import lombok.Getter;
import lombok.Setter;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;


/**
 * <p>发送邮件</p>
 * @author 何克最
 * @version $Id: SendMailUtil.java, v 0.1 2016年10月20日 下午3:14:26 Administrator Exp $
 */
public class SendMailUtil {
    private static final Logger logger = Logger.getLogger(SendMailUtil.class);
    private final Properties props = new Properties();
    
    @Setter@Getter
    private List<String> mailToList = new ArrayList<String>();
    @Setter@Getter
    private List<String> mailCcList = new ArrayList<String>();
    
    public SendMailUtil(String host, String mailUser, String mailPassword) {
        // 配置发送邮件的环境属性
        /*
         * 可用的属性： mail.store.protocol / mail.transport.protocol / mail.host /
         * mail.user / mail.from
         */
        // 表示SMTP发送邮件，需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", host);
        // 发件人的账号
        props.put("mail.user", mailUser);
        // 访问SMTP服务时需要提供的密码
        props.put("mail.password", mailPassword);
    }
    
    public SendMailUtil(String host, String mailUser, String mailPassword, String mailTo, String mailCc) {
        // 配置发送邮件的环境属性
        /*
         * 可用的属性： mail.store.protocol / mail.transport.protocol / mail.host /
         * mail.user / mail.from
         */
        // 表示SMTP发送邮件，需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", host);
        // 发件人的账号
        props.put("mail.user", mailUser);
        // 访问SMTP服务时需要提供的密码
        props.put("mail.password", mailPassword);
        
        if(StringUtils.isNotBlank(mailTo)) {
            String[] mailTos = mailTo.split(",");
            if(mailTos.length > 0) {
                for(String to:mailTos) {
                    mailToList.add(to);
                }
            }
        }
        if(StringUtils.isNotBlank(mailCc)) {
            String[] mailCcs = mailCc.split(",");
            if(mailCcs.length > 0) {
                for(String cc:mailCcs) {
                    mailCcList.add(cc);
                }
            }
        }
    }
    
    public void addMailTo(String mailTo){
        mailToList.add(mailTo);
    }
    
    public void addMailCc(String mailCc){
        mailCcList.add(mailCc);
    }
    
    public void sendMail(String subject, String content, List<File> attachments) {
        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        
        Multipart multipart = new MimeMultipart();

        try {
            // 设置发件人 
            InternetAddress form = new InternetAddress(
                props.getProperty("mail.user"));
            message.setFrom(form);

            // 设置收件人
            if(mailToList != null && mailToList.size() > 0) {
                InternetAddress[] to = new InternetAddress[mailToList.size()];
                for(int i = 0; i < mailToList.size(); i++) {
                    to[i] = new InternetAddress(mailToList.get(i));
                }
                message.setRecipients(RecipientType.TO, to);
            } else {
                logger.error("no mailTo");
                return;
            }

            // 设置抄送
            if(mailCcList != null && mailCcList.size() > 0) {
                InternetAddress[] cc = new InternetAddress[mailCcList.size()];
                for(int i = 0; i < mailCcList.size(); i++) {
                    cc[i] = new InternetAddress(mailCcList.get(i));
                }
                message.setRecipients(RecipientType.CC, cc);
            }

            // 设置邮件标题
            message.setSubject(subject);
            
            // 添加邮件正文
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(content, "text/html;charset=UTF-8");
            multipart.addBodyPart(contentPart);
            
            // 添加附件的内容
            if (attachments != null && attachments.size() > 0) {
                MimeBodyPart filePart;  
                FileDataSource filedatasource;
                for (int i = 0; i < attachments.size(); i++) {
                    File attachment = attachments.get(i);
                    if(attachment == null || !attachment.exists()) continue;
                    filePart = new MimeBodyPart();  
                    filedatasource = new FileDataSource(attachment);  
                    filePart.setDataHandler(new DataHandler(filedatasource));  
                    try {  
                        filePart.setFileName(MimeUtility.encodeText(filedatasource.getName()));  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                    multipart.addBodyPart(filePart);  
                }
            }
            
            // 将multipart对象放到message中
            message.setContent(multipart);

            // 发送邮件
            Transport.send(message);
            logger.info("SendMailUtil send mail success.");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("SendMailUtil send mail error",e);
        }
    }
    
    public void sendMail(String subject, String centent) {
        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);

        try {
            // 设置发件人
            InternetAddress form = new InternetAddress(
                props.getProperty("mail.user"));
            message.setFrom(form);

            // 设置收件人
            if(mailToList != null && mailToList.size() > 0) {
                InternetAddress[] to = new InternetAddress[mailToList.size()];
                for(int i = 0; i < mailToList.size(); i++) {
                    to[i] = new InternetAddress(mailToList.get(i));
                }
                message.setRecipients(RecipientType.TO, to);
            } else {
                logger.error("no mailTo");
                return;
            }

            // 设置抄送
            if(mailCcList != null && mailCcList.size() > 0) {
                InternetAddress[] cc = new InternetAddress[mailCcList.size()];
                for(int i = 0; i < mailCcList.size(); i++) {
                    cc[i] = new InternetAddress(mailCcList.get(i));
                }
                message.setRecipients(RecipientType.CC, cc);
            }

            // 设置邮件标题
            message.setSubject(subject);

            // 设置邮件的内容体
            message.setContent(centent, "text/html;charset=UTF-8");

            // 发送邮件
            Transport.send(message);
            logger.info("SendMailUtil send mail success.");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("SendMailUtil send mail error",e);
        }
    }
}
